//
//  SaveViewController.m
//  CarFace
//
//  Created by dlios on 15-4-2.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "SaveViewController.h"
#import "DataHander.h"
#import "UIButton+InitButton.h"
#import "DownViewController.h"


@interface SaveViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)NSMutableArray *array;
@property (nonatomic, retain)NSMutableArray *arr;
@property (nonatomic, retain) DataHander *db;
@property (nonatomic, retain)NSString *idStr;
@property (nonatomic, retain)UIButton *editButton;
@property (nonatomic, retain)UIButton *selectCancleButton;
@property (nonatomic, retain)NSMutableArray *selectedArr;
@property (nonatomic, retain)NSMutableDictionary *selectedDic;
@property (nonatomic, assign)NSInteger row;
@property (nonatomic, assign)BOOL flag;
@end

@implementation SaveViewController
- (void)dealloc
{
    [_tableView release];
    [_array release];
    [_arr release];
    [_idStr release];
    [_selectedArr release];
    [_selectedDic release];


    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *returnButton = [UIButton buttonWithTitle:@"返回" frame:CGRectMake(0, self.view.frame.size.height / 17, self.view.frame.size.width / 4,20) target:self action:@selector(clickReturnButton:)];
    [returnButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [returnButton setImage:[UIImage imageNamed:@"iconfont-fanhui.png"] forState:UIControlStateNormal];
    [self.view addSubview:returnButton];
    
    self.editButton = [UIButton buttonWithTitle:@"编辑" frame:CGRectMake(self.view.frame.size.width * 4 / 5, self.view.frame.size.height / 16, self.view.frame.size.width / 4,20) target:self action:@selector(clickEditButton:)];
//    [editButton setImage:[UIImage imageNamed:@"iconfont-shanchu.png"] forState:UIControlStateNormal];
    [self.editButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.view addSubview:self.editButton];
    
   // UIButton *allSelectButton = [UIButton buttonWithTitle:@"全选" frame:CGRectMake(0, self.view.frame.size.height - 50, self.VIEW_WIDTH / 2, 30) target:self action:@selector(clickAllSelectButton:)];
   // [allSelectButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
  //  [self.view addSubview:allSelectButton];
    
 
  //  self.selectCancleButton = [UIButton buttonWithTitle:@"删除" frame:CGRectMake(self.view.frame.size.width / 2, self.view.frame.size.height - 50, self.self.view.frame.size.width / 2, 30) target:self action:@selector(clickSelectCancleButton:)];
  //  [self.selectCancleButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
  //  [self.view addSubview:self.selectCancleButton];
//
    
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 2  - 30, 50, 60, 40)];
    title.text = @"收藏夹";
    title.textAlignment = NSTextAlignmentCenter;
    title.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:title];
    [title release];
    
   
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(5, 100, self.view.frame.size.width - 10, self.view.frame.size.height - 55 - 100) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView addHeaderWithTarget:self action:@selector(addHeader:)];
    [self.tableView addFooterWithTarget:self action:@selector(addFooter:)];
    [self.tableView setHeaderRefreshingText:@"下拉刷新"];
    [self.tableView setFooterRefreshingText:@"网络加载中..."];
    
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    
  
    //  引用数据库,打开数据库
    self.db = [DataHander shareInstance];
    [self.db openDB];
    self.array = [NSMutableArray array];
    // 取到所有的数据放到数组里
    self.array = [[DataHander shareInstance] selectAll];
    
    [_tableView reloadData];
 
//    self.selectedDic = [NSMutableDictionary dictionary];
   self.selectedArr = [NSMutableArray array];
    self.arr = [NSMutableArray array];
}


#pragma mark - tableView

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"reque";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str]autorelease];
    }
    cell.textLabel.text = [[self.array objectAtIndex:indexPath.row] bbsname];
     self.idStr = [[self.array objectAtIndex:indexPath.row] bbsid];
    return cell;
    
}



- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
   // return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
    return UITableViewCellEditingStyleDelete;
}


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"dd");
    if (editingStyle == UITableViewCellEditingStyleDelete) {
    //   当点击删除按钮时,对试图做操作时,要先对数据源做处理
        [self.array removeObjectAtIndex:indexPath.row];
        [self.db deleteData:self.idStr];
        NSLog(@"%@**", self.idStr);
         NSLog(@"%@", [self.db selectAll]);
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
    }
}



- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    //移动之后执行的方法
    //    1,从数据源取值
    NSString *name = [[[self.array objectAtIndex:sourceIndexPath.row] bbsname ]retain];
    //    2.从原来的位置移除
    [self.array removeObjectAtIndex:sourceIndexPath.row];
    //    3.放到新的位置
    [self.array insertObject:name atIndex:destinationIndexPath.row];
    [name release];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.flag == NO) {
    DownViewController *downVC = [[DownViewController alloc]init];
    downVC.stringId = [[self.array objectAtIndex:indexPath.row]bbsid];
    downVC.stringname = [[self.array objectAtIndex:indexPath.row]bbsname];
    [self presentViewController:downVC animated:YES completion:^{
    }];
    [downVC release];

 }
    
//    NSString *str = [self.array objectAtIndex:indexPath.row];
//    [self.selectedDic setObject:indexPath forKey:str];
//    NSLog(@"%@", str);
//    NSLog(@"%@", indexPath);
//    NSLog(@"self.selectedDic : %@", self.selectedDic);
//
//    NSLog(@"%ld", [[self.selectedDic allKeys]count]);
   
    
    
  //  NSString *numStr = [NSString stringWithFormat:@"%ld", indexPath.row];
     //   [self.arr addObject:numStr];
    //    [self.selectedArr addObject:[self.array objectAtIndex:indexPath.row]];

  //  NSLog(@"self.arr : %@", self.arr);
  //  NSLog(@"self.selectArr : %@", self.selectedArr);
    
//    self.arr:保存所有保存在收藏夹中被选中的对象
//    self.array:保存被收藏的对象
//    self.selectArr: 保存所有被选中即将要删除的对象的bbsid

    
    

    
    
}


- (void)clickSelectCancleButton:(UIButton *)button
{
//  方1  数组
    //        self.arr:保存所有保存在收藏夹中被选中的对象
    //        self.array:保存被收藏的对象
    //        self.selectArr: 保存所有被选中即将要删除的对象的bbsid
    
    NSInteger count = [self.selectedArr count];
    if (count > 0) {
        for (NSInteger i = 0; i < count; i++) {
            
            NSString *bbsid = [self.selectedArr objectAtIndex:i];
            [self.db deleteData:bbsid];

          
            //  self.array 中的元素下标与相应的self.arr 中的可能不同.要由self.arr中的元素的值来确定self.array中的元素
            NSString *num = [self.arr objectAtIndex:i];
            NSInteger n = [num integerValue];
            [self.array removeObjectAtIndex:n];
            
        }
        
        [self.arr removeAllObjects];
        [self.selectedArr removeAllObjects];
        [self.tableView setEditing:YES animated:YES];
        [self.tableView reloadData];
        NSLog(@"%@", [self.db selectAll]);
    
        
//方2:  字典
//    NSInteger count = [[self.selectedDic allKeys]count];;
//                if (count == 0) {
//                    for (NSInteger i = 0; i < count; i++) {
//        
//                        NSString *bbsid = [self.selectedDic objectForKey:@"bbsid"];
//                        [self.db deleteData:bbsid];
//                    }
////
//                    [self.array removeObjectsInArray:[self.selectedDic allKeys]];
//        
//                    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithArray:[self.selectedDic allValues]] withRowAnimation:UITableViewRowAnimationFade];
//                    [self.selectedDic removeAllObjects];
    
        
        
    }else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"未选中任何数据!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"重新选择", nil];
        [alert show];
        [alert release];
    }
    
    
}




#pragma mark- 按钮方法
- (void)clickReturnButton:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}

- (void)clickEditButton:(UIButton *)button
{
    if (self.flag == NO) {
        [_tableView setEditing:YES animated:YES];
        [_tableView allowsSelectionDuringEditing];
        [self.editButton setTitle:@"取消" forState:UIControlStateNormal];
    }else{
        [_tableView setEditing:NO animated:YES];
        [self.editButton setTitle:@"编辑" forState:UIControlStateNormal];
        
    }
    self.flag =! self.flag;
}


- (void)clickAllSelectButton:(UIButton *)button
{
    NSLog(@"count = %ld", self.array.count);
    NSLog(@"dd");
    if (self.flag == NO && [self.array count] != 0) {
        [_tableView allowsMultipleSelection];
        [_tableView selectAll:self.array];
        
        NSLog(@"ff");
        
    }else if ([self.array count] == 0){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有数据可选!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [alert show];
        [alert release];
        NSLog(@"ddddd");
    }
}


    




#pragma mark - 刷新的方法
- (void)addHeader:(UITableView *)header
{
    __unsafe_unretained typeof(self) vc = self;
    // 添加下拉刷新头部控件
    [self.tableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        NSLog(@"KKk______kk");
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [vc.tableView reloadData];
            // 结束刷新
            [vc.tableView headerEndRefreshing];
            NSLog(@"KKkkk");
        });
    } dateKey:@"collection"];
    // dateKey用于存储刷新时间，也可以不传值，可以保证不同界面拥有不同的刷新时间
    
}

- (void)addFooter:(UITableView *)footer
{
    __unsafe_unretained typeof(self) vc = self;
    // 添加上拉刷新尾部控件
    [self.tableView addFooterWithCallback:^{
        [self.tableView addHeaderWithTarget:self action:@selector(searchBarSearchButtonClicked:)];
        
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [vc.tableView reloadData];
            // 结束刷新
            [vc.tableView footerEndRefreshing];
            
        });
    }];
}












- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
